import request from '@/common/request.js'
const dayjs = require('@/common/dayjs.min.js')
const doHandleMonth = (month) => {
	var m = month
	if (month.toString().length == 1) {
		m = '0' + month
	}
	return m
}

export const timeFormatTxt = (number, unit1 = '分', unit2 = '秒') => {
	let minute = parseInt(number / 60)
	let second = parseInt(number % 60)
	minute = minute >= 10 ? minute : '0' + minute
	second = second >= 10 ? second : '0' + second
	return minute + unit1 + second + unit2
}

export const formatDate = (date, fmt) => {
	const padLeftZero = (str) => {
		return ('00' + str).substr(str.length)
	}
	if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(
			RegExp.$1,
			(date.getFullYear() + '').substr(4 - RegExp.$1.length)
		)
	}
	let o = {
		'M+': date.getMonth() + 1,
		'd+': date.getDate(),
		'h+': date.getHours(),
		'm+': date.getMinutes(),
		's+': date.getSeconds(),
	}
	for (let k in o) {
		if (new RegExp(`(${k})`).test(fmt)) {
			let str = o[k] + ''
			fmt = fmt.replace(
				RegExp.$1,
				RegExp.$1.length === 1 ? str : padLeftZero(str)
			)
		}
	}
	return fmt
}

export const getCurrentDay = () => {
	const date = new Date()
	const y = date.getFullYear()
	const m = doHandleMonth(date.getMonth() + 1)
	const d = doHandleMonth(date.getDate())
	const w = date.getDay()
	const h = doHandleMonth(date.getHours())
	const minute = doHandleMonth(date.getMinutes())
	return [y, m, d, w, h, minute]
}

export const getStarLevel = (level) => {
	let levelName = [
		'',
		'一级',
		'二级',
		'三级',
		'四级',
		'五级',
		'六级',
		'七级',
		'八级',
		'九级',
	]
	return levelName[level]
}

export const setMoney = (cent) => {
	return cent ? (cent / 100).toFixed(2) : cent
}

export const getNameBydot = (name, length) => {
	if (name.length > length) {
		return name.slice(0, length) + '...'
	} else {
		return name
	}
}
export const getNameByCenterDot = (str, length = 22) => {
	console.log(str)
	var last = 0
	var all = str.length
	var fisrt = str.substring(0, 13)
	// 没有中文括号（
	if (str.lastIndexOf('（') == -1) {
		// 也没有英文括号(
		if (str.lastIndexOf('(') == -1) {
			last = all - 10
		} else {
			// 有英文括号(，就从英文括号开始截取
			last = str.lastIndexOf('(')
		}
	} else {
		last = str.lastIndexOf('（')
	}
	// 如果长度大于13个字符才显示省略号
	if (all > length) {
		return fisrt + ' ... ' + str.substring(last, all)
	} else {
		return str
	}
}

export const getTargetDay = (day) => {
	const today = new Date()
	const targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day
	today.setTime(targetday_milliseconds) //注意，这行是关键代码
	let tYear = today.getFullYear()
	let tMonth = today.getMonth()
	let tDate = today.getDate()
	tMonth = doHandleMonth(tMonth + 1)
	tDate = doHandleMonth(tDate)
	return tYear + '-' + tMonth + '-' + tDate
}

export const saveSubRecord = (tmplIds) => {
	uni.requestSubscribeMessage({
		tmplIds: tmplIds,
		success(res) {
			console.log(res)
			let lasttmplIds = []
			tmplIds.map((item) => {
				if (res[item] === 'accept') {
					lasttmplIds.push(item)
				}
			})
			request
				.request('oss-web/miniapp/subscribe/saveSubRecord', {
					data: {
						channel: 100003,
						openId: uni.getStorageSync('openId'),
						infoList: lasttmplIds,
					},
					method: 'post',
				})
				.then((res) => res)
		},
	})
}

/**
 *
 * @param {*} dayjsDate dayjs对象
 */
export const generateMonthData = (dayjsDate) => {
	//返回当前月份的第一天
	const currentMonthFirstDay = dayjsDate.startOf('month')
	const currentMonthLastDay = dayjsDate.endOf('month')
	// 返回当月的第一周第一天
	const currentMonthStartDay = currentMonthFirstDay.startOf('week')

	//上一个月
	const prevMonthFirstDay = currentMonthFirstDay.subtract(1, 'month')
	const prevMonthStartDay = prevMonthFirstDay.startOf('week')

	//下一个月
	const nextMonthFirstDay = currentMonthFirstDay.add(1, 'month')
	const nextMonthStartDay = nextMonthFirstDay.startOf('week')

	return {
		currentMonthFirstDay,
		currentMonthLastDay,
		generateMonthDateList: [
			new Array(42)
				.fill('')
				.map((_, index) => prevMonthStartDay.add(index, 'day')),
			new Array(42)
				.fill('')
				.map((_, index) => currentMonthStartDay.add(index, 'day')),
			new Array(42)
				.fill('')
				.map((_, index) => nextMonthStartDay.add(index, 'day')),
		],
	}
}

/**
 *
 * @param {*} dayjsDate dayjs对象
 */
export const generateWeekData = (dayjsDate) => {
	console.log(dayjsDate)
	const currenWeekStartDay = dayjsDate.startOf('week')
	const currenWeekLastDay = dayjsDate.endOf('week')
	const prevWeekStartDay = currenWeekStartDay.subtract(1, 'week')
	const nextWeekStartDay = currenWeekStartDay.add(1, 'week')
	return {
		currenWeekFirstDay: currenWeekStartDay,
		currenWeekLastDay: currenWeekLastDay,
		generateWeekDateList: [
			new Array(7)
				.fill('')
				.map((_, index) => prevWeekStartDay.add(index, 'day')),
			new Array(7)
				.fill('')
				.map((_, index) => currenWeekStartDay.add(index, 'day')),
			new Array(7)
				.fill('')
				.map((_, index) => nextWeekStartDay.add(index, 'day')),
		],
	}
}
export const handelFormtDate = (date, exp) => {
	return dayjs(date).format(exp)
}
export const scrollError = (val) => {
	uni.createSelectorQuery()
		.selectAll('.top-scroll')
		.boundingClientRect((res) => {
			console.log(res)
			let topHeight = res && res.length > 0 ? Math.abs(res[0].top) : 0
			uni.createSelectorQuery()
				.selectAll(val)
				.boundingClientRect((res) => {
					console.log(res)
					let columnRefTops = res.map((item) => item.top)
					let refHeight = columnRefTops[0]
					if (topHeight > 0) {
						refHeight = topHeight + refHeight
					}

					uni.pageScrollTo({
						duration: 1000,
						scrollTop: refHeight,
					})
				})
				.exec()
		})
		.exec()
}

export const getFileName = (fileName) => {
	var showFileName = ''
	var disLength = fileName.length
	var substringC = 6
	var nameLength = 0
	var cutIndex = 0
	for (var i = 0; i < disLength; i++) {
		if (escape(fileName[i]).indexOf('%u') < 0) {
			//不是中文
			nameLength += 1
		} else {
			//中文
			nameLength += 2
		}
		if (nameLength > 12) {
			cutIndex = i
			break
		}
	}
	if (nameLength > substringC) {
		showFileName = fileName.replace(
			/^(^.{15})(.+)(.{2}\.+\w+$)$/g,
			'$1...$3'
		)
	} else {
		showFileName = fileName
	}
	return showFileName
}

export const imgSuffixName = [
	'png',
	'jpg',
	'jpeg',
	'bmp',
	'gif',
	'webp',
	'psd',
	'svg',
	'tiff',
]

//数字转中文金额
export const convertCurrency = (money) => {
	var cnNums = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
	var cnIntRadice = ['', '拾', '佰', '仟']
	var cnIntUnits = ['', '万', '亿', '兆']
	var cnDecUnits = ['角', '分', '毫', '厘']
	var cnInteger = '整'
	var cnIntLast = '元'
	var maxNum = 999999999999.9999
	var integerNum
	var decimalNum
	var chineseStr = ''
	var parts
	if (money === '') {
		return ''
	}
	money = parseFloat(money)
	if (money >= maxNum) {
		return ''
	}
	if (money === 0) {
		chineseStr = cnNums[0] + cnIntLast + cnInteger
		return chineseStr
	}
	money = money.toString()
	if (money.indexOf('.') === -1) {
		integerNum = money
		decimalNum = ''
	} else {
		parts = money.split('.')
		integerNum = parts[0]
		decimalNum = parts[1].substr(0, 4)
	}
	if (parseInt(integerNum, 10) > 0) {
		var zeroCount = 0
		var IntLen = integerNum.length
		for (var i = 0; i < IntLen; i++) {
			var n = integerNum.substr(i, 1)
			var p = IntLen - i - 1
			var q = p / 4
			var m = p % 4
			if (n === '0') {
				zeroCount++
			} else {
				if (zeroCount > 0) {
					chineseStr += cnNums[0]
				}
				zeroCount = 0
				chineseStr += cnNums[parseInt(n)] + cnIntRadice[m]
			}
			if (m === 0 && zeroCount < 4) {
				chineseStr += cnIntUnits[q]
			}
		}
		chineseStr += cnIntLast
	}
	if (decimalNum !== '') {
		var decLen = decimalNum.length
		for (i = 0; i < decLen; i++) {
			n = decimalNum.substr(i, 1)
			if (n !== '0') {
				chineseStr += cnNums[Number(n)] + cnDecUnits[i]
			}
		}
	}
	if (chineseStr === '') {
		chineseStr += cnNums[0] + cnIntLast + cnInteger
	} else if (decimalNum === '') {
		chineseStr += cnInteger
	}
	return chineseStr
}

//生成唯一的id
export const uuid = () => {
	const len = 32 //32长度
	let radix = 16 //16进制
	const chars =
		'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(
			''
		)
	let uuid = [],
		i
	radix = radix || chars.length
	if (len) {
		for (i = 0; i < len; i++) {
			uuid[i] = chars[0 | (Math.random() * radix)]
		}
	} else {
		let r
		uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
		uuid[14] = '4'
		for (i = 0; i < 36; i++) {
			if (!uuid[i]) {
				r = 0 | (Math.random() * 16)
				uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r]
			}
		}
	}
	return uuid.join('')
}

//转化为文件的大小
export const formatSizeUnits = (bytes) => {
	if (bytes >= 1073741824) {
		bytes = (bytes / 1073741824).toFixed(2) + ' GB'
	} else if (bytes >= 1048576) {
		bytes = (bytes / 1048576).toFixed(2) + ' MB'
	} else if (bytes >= 1024) {
		bytes = (bytes / 1024).toFixed(2) + ' KB'
	} else if (bytes > 1) {
		bytes = bytes + ' bytes'
	} else if (bytes == 1) {
		bytes = bytes + ' byte'
	} else {
		bytes = '0 bytes'
	}
	return bytes
}

//防抖
export const debounce = (fn, delay) => {
	let timeout = null
	return function () {
		clearTimeout(timeout) //清除上个标记
		timeout = setTimeout(() => {
			// 确定间隔时间内不重复触发函数fn
			fn.apply(this, arguments)
		}, delay)
	}
}

// 预览文件
export const previewFile = (targetUrl) => {
	uni.downloadFile({
		url: targetUrl,
		success: function (res) {
			var filePath = res.tempFilePath
			let suffix = filePath.match(/\.([^.]+)$/)[1]
			const documentArr = [
				'doc',
				'xls',
				'ppt',
				'pdf',
				'docx',
				'xlsx',
				'pptx',
			]

			if (documentArr.includes(suffix)) {
				uni.openDocument({
					filePath: filePath,
					showMenu: true,
					success: function (res) {
						console.log('打开文档成功')
					},
					fail: function (err) {
						uni.showToast({
							title: err,
							icon: 'error',
						})
						console.log('打开文档失败', err)
					},
				})
			} else {
				uni.previewImage({
					urls: [filePath],
					success: function (res) {
						console.log('打开文档成功')
					},
					fail: function (err) {
						uni.showToast({
							title: err,
							icon: 'error',
						})
						console.log('打开文档失败', err)
					},
				})
			}
		},
	})
}

/*
 * 获取当日所在周的开始和结束日期
 * @param {*} dayjsDate dayjs对象
 */
export const getCurrentWeekRange = (dayjsDate) => {
	const currentWeekStartDay = dayjsDate
		.startOf('week')
		.add(1, 'day')
		.format('YYYY-MM-DD')
	const currentWeekLastDay = dayjsDate
		.endOf('week')
		.add(1, 'day')
		.format('YYYY-MM-DD')
	return {
		currentWeekStartDay: currentWeekStartDay,
		currentWeekLastDay: currentWeekLastDay,
	}
}

/**
 * 判断是否图片
 */
export const isPicture = (file) => {
	let imageTypes = [
		'png',
		'jpg',
		'jpeg',
		'svg',
		'bmp',
		'gif',
		'tif',
		'webp',
		'avif',
		'apng',
	]
	const isP = imageTypes.some((i) => {
		return file.indexOf(i) > -1
	})
	return isP
}

/**
 * 解析路由参数
 * @param {String} url
 */
export const getUrlParam = (url) => {
	let params = url.split('?')[1].split('&')
	let obj = {}
	params.map((v) => (obj[v.split('=')[0]] = v.split('=')[1]))
	return obj
}

/**
 * 数组去重
 * @param {*} arr
 * @returns
 */
export const unique = (arr) => {
	return Array.from(new Set(arr))
}

/**
 * 数字转成汉字
 * @params num === 要转换的数字
 * @return 汉字
 * */
export const toChinesNum = (num) => {
	let changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
	let unit = ['', '十', '百', '千', '万']
	num = parseInt(num)
	let getWan = (temp) => {
		let strArr = temp.toString().split('').reverse()
		let newNum = ''
		let newArr = []
		strArr.forEach((item, index) => {
			newArr.unshift(
				item === '0' ? changeNum[item] : changeNum[item] + unit[index]
			)
		})
		let numArr = []
		newArr.forEach((m, n) => {
			if (m !== '零') numArr.push(n)
		})
		if (newArr.length > 1) {
			newArr.forEach((m, n) => {
				if (newArr[newArr.length - 1] === '零') {
					if (n <= numArr[numArr.length - 1]) {
						newNum += m
					}
				} else {
					newNum += m
				}
			})
		} else {
			newNum = newArr[0]
		}

		return newNum
	}
	let overWan = Math.floor(num / 10000)
	let noWan = num % 10000
	if (noWan.toString().length < 4) {
		noWan = '0' + noWan
	}
	return overWan ? getWan(overWan) + '万' + getWan(noWan) : getWan(num)
}

/**
 * 将 - 替换成 /并转化时间格式时间戳
 */
export const replaceDateTime = (time) => {
	return new Date(time.replace(/-/g, '/'))
}

/**
 * 返回按钮，兼容第一个的情况
 * @param {*} url
 */
export const goBack = (url = '/pages/index/index') => {
	const pages = getCurrentPages()
	if (pages.length > 1) {
		uni.navigateBack({
			delta: 1,
			fail() {
				uni.redirectTo({
					url,
				})
			},
		})
	} else {
		uni.redirectTo({
			url,
		})
	}
}

//千分位金额格式化
export const formatCash = (val) => {
	let option = {
		minimumFractionDigits: 0,
	}
	if (val) {
		return parseFloat((val / 100).toFixed(2)).toLocaleString('zh', option)
	} else {
		return 0
	}
}

// 获取新的json对象
export const getJSON = (data) => {
	if ('object' === typeof data) {
		return JSON.parse(JSON.stringify(data))
	}
	return data
}

/* 二维数组排序(根据某个字段排序) */
export const listSortBy = (arr, field, sort = 'asc') => {
	arr.sort(function (a, b) {
		return a[field] - b[field]
	})
	if (sort === 'desc') {
		arr.reverse()
	}
	return arr
}

export const callPhone = (phoneNumber) => {
	uni.makePhoneCall({
		phoneNumber,
	})
}

// 给字符串每三个插入空格
export const insertSpace = (str) => {
	if (!str || str.length <= 3 || typeof str !== 'string') return str
	const _str = str.replace(/\s/g, '').replace(/(.{3})/g, '$1 ')
	return _str
}
